<script setup>
// import zz from '@/assets/chat/buddha/zz.jpg' // 对象头像
// import yjy from '@/assets/chat/buddha/yjy.jpg' // 本人头像
import { onMounted, onUpdated, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '@/services/user.js'
import { getOtherMagList } from '@/services/msg.js'
import { useRouter } from 'vue-router'

import { useUserStore } from '@/stores'
let userStore = useUserStore()

let router = useRouter()

// 当我进入到这个
// 获取当前用户信息
let userInfo = ref({}) // 当前用户id

// 信息
let msgText = ref('')

// 历史
let historyList = ref([])

// 最后一条
const historyListLast = computed(() => {
  if (historyList.value?.length > 0) {
    return historyList.value[historyList.value?.length - 1]?.message
  } else {
    return ''
  }
})

// 拿到当前用户的token
let thisToken = userStore.tokenObj.token || ''

// 当前聊天室二者数据模型
let idsMap = [
  {
    name: '宝贝',

    img: '/assets/zz.jpg',
    id: 'd226822166664015aa2a6be5'
  },
  {
    name: '宝宝',
    img: '/assets/yjy.jpg',
    id: '0288f6b07ed54f9c8f41e45a'
  }
]

let currentUser = ref({})
let objectUser = ref({})

let parseUser = () => {
  // 从idsMap 中解析出当前用户的模型和对象模型
  currentUser.value = idsMap.filter(
    (item) => item.id == userInfo.value.userid
  )[0]
  objectUser.value = idsMap.filter(
    (item) => item.id !== userInfo.value.userid
  )[0]
}

// 初始化生命
onMounted(async () => {
  // 利用token获取当前用户的信息
  await getUserInfoFn()

  // 获取二者的聊天记录
  let res = await getOtherMagList({
    joint_id: 'mains'
  })
  historyList.value = res.data
  console.log(res)
})

onUpdated(() => {
  // 解析用户
  parseUser()
  // 让盒子滚动最底部
  bottomDuration()
})

// 得到当前用户的个人简易信息
let getUserInfoFn = async () => {
  let res = await getUserInfo()
  userInfo.value['userName'] = res.data.account
  userInfo.value['userid'] = res.data.id
  userInfo.value['head_img'] = res.data.head_img
}

// ws 连接
// let ws = new WebSocket(`ws://localhost:9000/chat?token=${thisToken}`)
let ws = new WebSocket(`ws://zengzhi.info:9000/chat?token=${thisToken}`)

ws.onopen = () => {
  console.log('建立了连接')
  // 要拿到对谁聊天的id
}

// 接收到消息后触发这个事件
ws.onmessage = (evt) => {
  // 参数是一个事件对象，可以得到服务端推送的消息
  let evtObj = JSON.parse(evt.data)
  if (evtObj.noToken) {
    // 没有token
    ElMessage.error('请登录再试')
    // 跳转到 /login
    router.push('/login')
    return
  }
  // 信息B-A，接收来自宝贝的信息
  console.log(evtObj)
  historyList.value.push(evtObj)
}

ws.onclose = () => {
  console.log('关闭了连接')
}

// 发送消息
let sendMsg = () => {
  if (msgText.value === '') return ElMessage.warning('不能发送空消息')
  let msgObj = {
    my_id: userInfo.value?.userid, // 发送用户id
    message: msgText.value, // 信息
    from_id: '', // 接收用户id
    is_system: 'false', // 是否是系统信息 true 是
    joint_id: 'mains', // 联合id
    time_stamp: '' // 时间戳
  }

  // let objj = {
  //   Content: {
  //     content: msgText.value,
  //     from: 'Nini',
  //     fromId: '379975608',
  //     to: 'dasu',
  //     toId: '371120228'
  //   },
  //   MsgType: 'MsgReceiverTextContent',
  //   code: 0
  // }

  // 准备二者的id
  let ids = ['d226822166664015aa2a6be5', '0288f6b07ed54f9c8f41e45a']

  msgObj['from_id'] = ids.filter((val) => val != msgObj.my_id)[0]

  // 发送
  ws.send(JSON.stringify(msgObj)) // 对象转JSON
  msgText.value = ''
}

// 让盒子滚动条始终在最底部
// 元素.scrollTo(0,scrollHeight);
let socllBox = ref(null)

let bottomDuration = () => {
  let padFix = document.querySelector('.padFix')
  padFix.scrollTo(0, padFix.scrollHeight)
}

// 敲下回车发送信息
let enterKey = (e) => {
  if (e.keyCode === 13 && e.code === 'Enter') {
    sendMsg()
  }
}
let imgFile = ref(null)
// 图片发送
let sendimg = () => {
  // 触发一个隐藏的input选择器
  imgFile.value.click()
}

let choseFile = (e) => {
  if (e) {
    //
  }
  // 选择文件
  // 转化为base64
}
</script>

<template>
  <div class="chat-room-box">
    <div class="chat-room">
      <div class="room-left">
        <!-- 当前用户 -->
        <div class="buddha">
          <div class="buddha-img">
            <img :src="currentUser?.img" alt="" />
          </div>
          <div class="main-details">
            <div class="userName">{{ userInfo.userName }}</div>
            <div class="userid">id: {{ userInfo.userid }}</div>
          </div>
        </div>
        <!-- 可聊天好友列表 -->
        <div class="friend-list">
          <div class="list-li">
            <!-- 头像 -->
            <div class="li-buddha">
              <div class="li-buddha-img">
                <img :src="objectUser?.img" alt="" />
              </div>
            </div>
            <div class="chatDetails">
              <!-- 用户名 -->
              <div class="friendName">{{ objectUser?.name }}</div>
              <!-- 近期聊天 -->
              <div class="recentChat">
                {{ historyListLast }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="room-right">
        <div class="padLR right-top">
          <div class="title">{{ '宝宝' }}</div>
        </div>
        <!-- 数据展示中台 -->
        <div class="right-center">
          <div class="padLR padFix scrollBarDiv" ref="socllBox">
            <div
              class="for-log"
              v-for="item in historyList"
              :key="item.time_stamp"
            >
              <div class="msg-li left" v-if="item.my_id !== userInfo.userid">
                <!-- 对象头像 -->
                <div class="head-img">
                  <img :src="objectUser?.img || ''" alt="" />
                </div>
                <!-- 消息 -->
                <div class="font-msg">
                  {{ item.message }}
                </div>
              </div>
              <div class="msg-li right" v-else>
                <!-- 当前用户头像 -->
                <div class="head-img">
                  <img :src="currentUser?.img || ''" alt="" />
                </div>
                <!-- 消息 -->
                <div class="font-msg">{{ item.message }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 输入栏 -->
        <div class="padLR right-bottom">
          <!-- 功能栏 -->
          <div class="function-field">
            <div class="field-li" @click="sendimg">
              <SvgIcon href="#icon-note-tubiaolunkuo-"></SvgIcon>
              <input
                @input="choseFile"
                type="file"
                v-show="false"
                ref="imgFile"
                :multiple="false"
              />
            </div>
            <!-- 信号 -->
            <div id="signal" class="field-li">
              <SvgIcon href="#icon-note-xinhaota"></SvgIcon>
            </div>
          </div>
          <!-- 输入 -->
          <div class="tar-box">
            <textarea
              placeholder="send something...."
              class="tar"
              name=""
              id=""
              cols=""
              rows=""
              v-model.trim="msgText"
              @keyup="enterKey"
            ></textarea>
          </div>
          <!-- 发送 -->
          <div class="send-box" @click="sendMsg">
            <div class="send">发送(S)</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.chat-room-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #d0d0d0;
}
.chat-room {
  width: 1000px;
  height: 600px;
  overflow: hidden;
  background-color: pink;
  display: flex;
  .room-left {
    height: 100%;
    width: 220px;
    background-color: #dedddd;

    // 头像部分
    .buddha {
      width: 100%;
      height: 60px;
      padding: 0 10px;
      background-color: #2e2e2e;
      display: flex;
      align-items: center;
      .buddha-img {
        width: 50px;
        height: 50px;
        img {
          width: 100%;
        }
      }
      .main-details {
        height: 50px;
        width: 150px;
        padding: 0 10px;
        color: wheat;
        line-height: 1.3;

        .userid {
          color: #999999;
          font-size: 8px;
          /* 文字溢出部分变点点 */
          text-overflow: ellipsis;
          /* 文字溢出不换行 */
          white-space: nowarp;
          /* 溢出隐藏 */
          overflow: hidden;
        }
      }
    }

    // 好游列表部分
    .friend-list {
      list-style: none;
      margin: 0;
      .list-li {
        list-style: none;
        // background-color: #dcdcdd;
        background-color: #ffffff;
        display: flex;

        &:hover {
          background-color: #c5c6c6;
          cursor: pointer;
        }

        .li-buddha {
          height: 60px;
          width: 70px;
          padding: 0 10px;
          display: flex;
          align-items: center;
          .li-buddha-img {
            width: 50px;
            height: 50px;
            img {
              width: 100%;
            }
          }
        }

        // 用户文字信息
        .chatDetails {
          display: flex;
          flex-direction: column;
          align-content: space-evenly;
          justify-content: space-around;
          width: 150px;
          .friendName {
            font-size: 16px;
          }

          .recentChat {
            font-size: 14px;
            color: #999999;
            width: 130px;
            /* 文字溢出部分变点点 */
            text-overflow: ellipsis;
            /* 文字溢出不换行 */
            white-space: nowrap;
            /* 溢出隐藏 */
            overflow: hidden;
          }
        }
      }
    }
  }

  .room-right {
    flex: 1;
    background-color: #f5f5f5;

    // tab 栏切换，上中下三个部分，使用组件的方式会更加简单，但是在这里先不这样写

    .padLR {
      padding: 0 20px;
    }
    .right-top {
      height: 60px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #e7e7e7;
      display: flex;
      align-items: center;
    }

    .right-center {
      height: 380px;
      //   background-color: #fd7c7c;
      overflow: hidden;

      .padFix {
        overflow: auto;
        width: 100%;
        height: 100%;

        .for-log {
          .right {
            flex-direction: row-reverse;

            .font-msg {
              margin-right: 10px;
              background-color: #95ec69;
              position: relative;
              &::after {
                content: '';
                position: absolute;
                width: 10px;
                height: 10px;
                top: 8px;
                right: -4px;
                border: 1px solid #95ec69;
                border-radius: 3px;
                transform: rotate(45deg);
                background-color: #95ec69;
              }
            }
          }
          .left {
            .font-msg {
              margin-left: 10px;
              background-color: #ffffff;
              position: relative;
              z-index: 1;
              &::before {
                content: '';
                position: absolute;
                width: 10px;
                height: 10px;
                top: 8px;
                left: -4px;
                border: 1px solid #fff;
                border-radius: 3px;
                transform: rotate(45deg);
                background-color: #ffffff;
              }
            }
          }
          .msg-li {
            margin: 10px 0;
            // background-color: #42cfb5;
            display: flex;
            align-items: flex-start;
            .head-img {
              width: 50px;
              height: 50px;
              background-color: #74cdd6;
              img {
                width: 100%;
              }
            }
            // 文字部分
            .font-msg {
              max-width: 290px;
              padding: 10px;
              word-break: break-all;
              overflow-wrap: break-word;
              line-height: 1.3;
              border-radius: 5px;
            }
          }
        }
      }
    }

    .right-bottom {
      height: 160px;
      background-color: #f5f5f5;
      position: relative;
      display: flex;
      align-items: flex-start;
      flex-direction: column;
      justify-content: center;
      border-top: 1px solid #d0d0d0;

      // 功能栏
      .function-field {
        display: flex;
        padding: 4px 0px;

        #signal {
          color: #07c160;
        }

        .field-li {
          width: 30px;
          height: 30px;
          line-height: 30px;
          margin-right: 5px;
          font-size: 22px;
          color: #c5c6c6;
          &:hover {
            cursor: pointer;
            color: #999999;
          }
        }
      }

      .tar-box {
        width: 100%;
        .tar {
          width: 100%;
          height: 120px;
          background-color: #f5f5f5;
          border: 0px solid transparent;
          line-height: 1.3;
        }
      }

      .send-box {
        position: absolute;
        right: 20px;
        bottom: 20px;
        background-color: #e9e9e9;
        padding: 10px 30px;
        border-radius: 8px;
        color: #07c160;
        &:hover {
          cursor: pointer;
          background-color: #d2d2d2;
        }
      }
    }
  }
}
</style>
